package com.neusoft.lohas.common.pay;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.Ostermiller.util.MD5;
import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.pay.payutil.mobile.config.AlipayConfig;
import com.neusoft.lohas.common.pay.payutil.mobile.util.AlipaySubmit;
import com.neusoft.lohas.common.pay.payutil.mobile.util.UtilDate;
import com.neusoft.lohas.common.pay.upowp.util.DesUtil2;
import com.neusoft.lohas.common.pay.upowp.util.EncDecUtil;
import com.neusoft.lohas.common.pay.upowp.util.RSACoder;
import com.neusoft.lohas.common.pay.upowp.util.RemoteAccessor;
import com.neusoft.lohas.modules.ivm.entity.order.Order;

public class PayBase {

	/**
	 * 银联支付手机网页支付订单提交封装
	 * @param request
	 * @param dealIndent
	 * @param appId
	 * @param userId
	 * @return
	 */
	public static String unionpaySubmit_MW(HttpServletRequest request, Order order, String param1, String param2, String param3, String param4, String param5, Object... params){
		String redirectPage="";
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		java.util.Date currentTime = new java.util.Date();//得到当前系统时间 
		Date outDate = new Date(currentTime.getTime() + 5 * 60 * 1000);
		String pDate = formatter.format(currentTime);
		String oDate = formatter.format(outDate);
		//前台跳转地址
		String frontUrl = Global.getWebUrlPath()+Global.getFrontPath()+"/shops?sid="+param1+"&amp;mobile="+param2+"&amp;classifyId="+param3+"&amp;shopModel="+param4+"&amp;appId="+param5;
		if (params.length>0) {
			frontUrl = Global.getWebUrlPath()+Global.getFrontPath()+"/shops/myorder?mobile="+param1+"&amp;username="+param2+"&amp;classifyId="+param3+"&amp;shopModel="+param4+"&amp;appId="+param5;
		}
		String backUrl = Global.getWebUrlPath()+Global.getFrontPath()+"/shops/pay/unionPay/selfUnionPayBack";
		RemoteAccessor remoteAccessor = new RemoteAccessor();
    	try{
    		double amounts = order.getAmount();
	    	String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
	    			"<upbp application=\"MGw.Req\" version =\"1.0.0\" sendTime =\""+pDate+"\" sendSeqId =\"00000888888000\">" +
	    			"<frontUrl>"+frontUrl+"</frontUrl><merchantOrderDesc></merchantOrderDesc><misc></misc>" +
	    			"<gwType>01</gwType><transTimeout>"+oDate+"</transTimeout><backUrl>"+backUrl+"</backUrl>" +
	    			"<merchantOrderCurrency>156</merchantOrderCurrency><merchantOrderAmt>"+new java.text.DecimalFormat("0").format(Double.valueOf(amounts*100))+"</merchantOrderAmt>" +
	    			"<merchantOrderDesc>商品订购</merchantOrderDesc>"+
	    			"<merchantName>乐活社区电商系统在线支付</merchantName><merchantId>802310048993225</merchantId><merchantOrderTime>"+pDate+"</merchantOrderTime>" +
	    			"<merchantOrderId>"+order.getOrderNo()+"</merchantOrderId><merchantUserId></merchantUserId>" +
	    			"<mobileNum>"+order.getUser().getMobile()+"</mobileNum>" +
	    			"<cardNum></cardNum></upbp>";
	    	BASE64Encoder encoder = new BASE64Encoder();
	    	BASE64Decoder decoder = new BASE64Decoder();
	    	String merchantId = encoder.encodeBuffer("802310048993225".getBytes());
	    	String mm = MD5.getHashString("654321");
	    	String keyPath = request.getRealPath("/") + "unionpay/802310048993225.pfx";
	    	String privateKey = EncDecUtil.getCertKey("123456",keyPath);
	    	String desKey = encoder.encodeBuffer(RSACoder.encryptByPrivateKey(mm.getBytes(), decoder.decodeBuffer(privateKey)));
	    	byte[] bodyb = DesUtil2.encrypt(data.getBytes("utf-8"), mm.getBytes());
	    	String miBody = encoder.encode(bodyb);
	    	String xml = merchantId + "|" + desKey + "|" + miBody;
	    	String re = remoteAccessor.getResponseByStream("http://upwap.bypay.cn/gateWay/gate.html", "utf-8", xml);
	    	//System.out.println("返回结果："+re);
	    	String[] strArr = re.split("\\|");
	    	byte[] de = decoder.decodeBuffer(strArr[1]);
	    	byte[] b = DesUtil2.decrypt(de, mm.getBytes());
	    	String content = new String(b,"utf-8");
	    	//System.out.println(content);
	    	Document document = DocumentHelper.parseText(content);
	    	Element upbp = document.getRootElement();
	    	redirectPage = upbp.elementText("gwInvokeCmd");
	    	//System.out.println("重定向地址：");
	    	//System.out.println(redirectPage);
    	}catch (Exception e) {
    		e.printStackTrace();
    	}
    	return redirectPage;
	}
	
	/**
	 * 支付宝支付手机网页支付订单提交封装
	 * @param dealIndent
	 * @param appId
	 * @param userId
	 * @return
	 */
	public static String alipaySubmit_MW(Order order, String param1, String param2, String param3, String param4, String param5, Object... params){
		try {
			////////////////////////////////////调用授权接口alipay.wap.trade.create.direct获取授权码token//////////////////////////////////////
			
			//返回格式
			String format = "xml";
			//必填，不需要修改
			
			//返回格式
			String v = "2.0";
			//必填，不需要修改
			
			//请求号
			String req_id = UtilDate.getOrderNum();
			//必填，须保证每次请求都是唯一
			
			//req_data详细信息
			String url=Global.getWebUrlPath()+Global.getFrontPath()+"/shops";
			//服务器异步通知页面路径
			String notify_url = url+"/pay/alipay/notify";
			//需http://格式的完整路径，不能加?id=123这类自定义参数
	
			//页面跳转同步通知页面路径
			String call_back_url = url+"/pay/alipay/callback?sid="+param1+"&amp;mobile="+param2+"&amp;classifyId="+param3+"&amp;shopModel="+param4+"&amp;appId="+param5;
			//需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
	
			//操作中断返回地址
			String merchant_url = url+"?sid="+param1+"&amp;mobile="+param2+"&amp;classifyId="+param3+"&amp;shopModel="+param4+"&amp;appId="+param5;
			if (params.length>0) {
				merchant_url = url+"/myorder?mobile="+param1+"&amp;username="+param2+"&amp;classifyId="+param3+"&amp;shopModel="+param4+"&amp;appId="+param5;
			}
			//用户付款中途退出返回商户的地址。需http://格式的完整路径，不允许加?id=123这类自定义参数
			
			double total_fee = order.getAmount();
			
			//请求业务参数详细
			String req_dataToken = "<direct_trade_create_req><notify_url>" + notify_url + "</notify_url><call_back_url>" + call_back_url + "</call_back_url><seller_account_name>" + AlipayConfig.seller_email + "</seller_account_name><out_trade_no>" + order.getOrderNo() + "</out_trade_no><subject>乐活社区电商系统在线支付</subject><total_fee>" + total_fee + "</total_fee><merchant_url>" + merchant_url + "</merchant_url></direct_trade_create_req>";
			//必填
			
			//////////////////////////////////////////////////////////////////////////////////
			
			//把请求参数打包成数组
			Map<String, String> sParaTempToken = new HashMap<String, String>();
			sParaTempToken.put("service", "alipay.wap.trade.create.direct");
			sParaTempToken.put("partner", AlipayConfig.partner);
			sParaTempToken.put("_input_charset", AlipayConfig.input_charset);
			sParaTempToken.put("sec_id", AlipayConfig.sign_type);
			sParaTempToken.put("format", format);
			sParaTempToken.put("v", v);
			sParaTempToken.put("req_id", req_id);
			sParaTempToken.put("req_data", req_dataToken);
			
			//建立请求
			String sHtmlTextToken = AlipaySubmit.buildRequest(AlipaySubmit.ALIPAY_GATEWAY_NEW,"", "",sParaTempToken);
			//URLDECODE返回的信息
			sHtmlTextToken = URLDecoder.decode(sHtmlTextToken,AlipayConfig.input_charset);
			//获取token
			String request_token = AlipaySubmit.getRequestToken(sHtmlTextToken);
			//out.println(request_token);
			
			////////////////////////////////////根据授权码token调用交易接口alipay.wap.auth.authAndExecute//////////////////////////////////////
			
			//业务详细
			String req_data = "<auth_and_execute_req><request_token>" + request_token + "</request_token></auth_and_execute_req>";
			//必填
			
			//把请求参数打包成数组
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "alipay.wap.auth.authAndExecute");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			sParaTemp.put("sec_id", AlipayConfig.sign_type);
			sParaTemp.put("format", format);
			sParaTemp.put("v", v);
			sParaTemp.put("req_data", req_data);
			
			//建立请求
			String sHtmlText = AlipaySubmit.buildRequestURL(AlipaySubmit.ALIPAY_GATEWAY_NEW, sParaTemp, "get");
			System.out.println(sHtmlText);
			return sHtmlText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//微信电商版本支付-----------------------------------
	/**
	 * 支付宝支付手机网页支付订单提交封装
	 * @param dealIndent
	 * @param appId
	 * @param userId
	 * @return
	 */
	public static String alipaySubmit_WX(Order order, int param1, Object... params){
		try {
			////////////////////////////////////调用授权接口alipay.wap.trade.create.direct获取授权码token//////////////////////////////////////
			
			//返回格式
			String format = "xml";
			//必填，不需要修改
			
			//返回格式
			String v = "2.0";
			//必填，不需要修改
			
			//请求号
			String req_id = UtilDate.getOrderNum();
			//必填，须保证每次请求都是唯一
			
			//req_data详细信息
			String url=Global.getWebUrlPath()+"/shops";
			//服务器异步通知页面路径
			String notify_url = url+"/pay/alipaywx/notify";
			//需http://格式的完整路径，不能加?id=123这类自定义参数
	
			//页面跳转同步通知页面路径
			String call_back_url = url+"/pay/alipaywx/callback?type="+param1;
			//需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
	
			//操作中断返回地址
			String merchant_url = Global.getWebUrlPath();
			if (params.length>0) {
				merchant_url = url+"/shoping/myOrder/orderList";
			}
			//用户付款中途退出返回商户的地址。需http://格式的完整路径，不允许加?id=123这类自定义参数
			
			double total_fee = order.getAmount();
			
			//请求业务参数详细
			String req_dataToken = "<direct_trade_create_req><notify_url>" + notify_url + "</notify_url><call_back_url>" + call_back_url + "</call_back_url><seller_account_name>" + AlipayConfig.seller_email + "</seller_account_name><out_trade_no>" + order.getOrderNo() + "</out_trade_no><subject>乐活社区电商系统在线支付</subject><total_fee>" + total_fee + "</total_fee><merchant_url>" + merchant_url + "</merchant_url></direct_trade_create_req>";
			//必填
			
			//////////////////////////////////////////////////////////////////////////////////
			
			//把请求参数打包成数组
			Map<String, String> sParaTempToken = new HashMap<String, String>();
			sParaTempToken.put("service", "alipay.wap.trade.create.direct");
			sParaTempToken.put("partner", AlipayConfig.partner);
			sParaTempToken.put("_input_charset", AlipayConfig.input_charset);
			sParaTempToken.put("sec_id", AlipayConfig.sign_type);
			sParaTempToken.put("format", format);
			sParaTempToken.put("v", v);
			sParaTempToken.put("req_id", req_id);
			sParaTempToken.put("req_data", req_dataToken);
			
			//建立请求
			String sHtmlTextToken = AlipaySubmit.buildRequest(AlipaySubmit.ALIPAY_GATEWAY_NEW,"", "",sParaTempToken);
			//URLDECODE返回的信息
			sHtmlTextToken = URLDecoder.decode(sHtmlTextToken,AlipayConfig.input_charset);
			//获取token
			String request_token = AlipaySubmit.getRequestToken(sHtmlTextToken);
			//out.println(request_token);
			
			////////////////////////////////////根据授权码token调用交易接口alipay.wap.auth.authAndExecute//////////////////////////////////////
			
			//业务详细
			String req_data = "<auth_and_execute_req><request_token>" + request_token + "</request_token></auth_and_execute_req>";
			//必填
			
			//把请求参数打包成数组
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "alipay.wap.auth.authAndExecute");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			sParaTemp.put("sec_id", AlipayConfig.sign_type);
			sParaTemp.put("format", format);
			sParaTemp.put("v", v);
			sParaTemp.put("req_data", req_data);
			
			//建立请求
			String sHtmlText = AlipaySubmit.buildRequestURL(AlipaySubmit.ALIPAY_GATEWAY_NEW, sParaTemp, "get");
			System.out.println(sHtmlText);
			return sHtmlText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 银联支付手机网页支付订单提交封装
	 * @param request
	 * @param dealIndent
	 * @param appId
	 * @param userId
	 * @return
	 */
	public static String unionpaySubmit_WX(HttpServletRequest request, Order order, Object... params){
		String redirectPage="";
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		java.util.Date currentTime = new java.util.Date();//得到当前系统时间 
		Date outDate = new Date(currentTime.getTime() + 5 * 60 * 1000);
		String pDate = formatter.format(currentTime);
		String oDate = formatter.format(outDate);
		//前台跳转地址
		String frontUrl = Global.getWebUrlPath();
		if (params.length>0) {
			frontUrl = Global.getWebUrlPath()+"/shops/shoping/myOrder/orderList";
		}
		String backUrl = Global.getWebUrlPath()+"/shops/pay/unionPaywx/selfUnionPayBack";
		RemoteAccessor remoteAccessor = new RemoteAccessor();
    	try{
    		double amounts = order.getAmount();
	    	String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
	    			"<upbp application=\"MGw.Req\" version =\"1.0.0\" sendTime =\""+pDate+"\" sendSeqId =\"00000888888000\">" +
	    			"<frontUrl>"+frontUrl+"</frontUrl><merchantOrderDesc></merchantOrderDesc><misc></misc>" +
	    			"<gwType>01</gwType><transTimeout>"+oDate+"</transTimeout><backUrl>"+backUrl+"</backUrl>" +
	    			"<merchantOrderCurrency>156</merchantOrderCurrency><merchantOrderAmt>"+new java.text.DecimalFormat("0").format(Double.valueOf(amounts*100))+"</merchantOrderAmt>" +
	    			"<merchantOrderDesc>商品订购</merchantOrderDesc>"+
	    			"<merchantName>乐活社区电商系统在线支付</merchantName><merchantId>802310048993225</merchantId><merchantOrderTime>"+pDate+"</merchantOrderTime>" +
	    			"<merchantOrderId>"+order.getOrderNo()+"</merchantOrderId><merchantUserId></merchantUserId>" +
	    			"<mobileNum>"+order.getUser().getMobile()+"</mobileNum>" +
	    			"<cardNum></cardNum></upbp>";
	    	BASE64Encoder encoder = new BASE64Encoder();
	    	BASE64Decoder decoder = new BASE64Decoder();
	    	String merchantId = encoder.encodeBuffer("802310048993225".getBytes());
	    	String mm = MD5.getHashString("654321");
	    	String keyPath = request.getRealPath("/") + "unionpay/802310048993225.pfx";
	    	String privateKey = EncDecUtil.getCertKey("123456",keyPath);
	    	String desKey = encoder.encodeBuffer(RSACoder.encryptByPrivateKey(mm.getBytes(), decoder.decodeBuffer(privateKey)));
	    	byte[] bodyb = DesUtil2.encrypt(data.getBytes("utf-8"), mm.getBytes());
	    	String miBody = encoder.encode(bodyb);
	    	String xml = merchantId + "|" + desKey + "|" + miBody;
	    	String re = remoteAccessor.getResponseByStream("http://upwap.bypay.cn/gateWay/gate.html", "utf-8", xml);
	    	//System.out.println("返回结果："+re);
	    	String[] strArr = re.split("\\|");
	    	byte[] de = decoder.decodeBuffer(strArr[1]);
	    	byte[] b = DesUtil2.decrypt(de, mm.getBytes());
	    	String content = new String(b,"utf-8");
	    	//System.out.println(content);
	    	Document document = DocumentHelper.parseText(content);
	    	Element upbp = document.getRootElement();
	    	redirectPage = upbp.elementText("gwInvokeCmd");
	    	//System.out.println("重定向地址：");
	    	//System.out.println(redirectPage);
    	}catch (Exception e) {
    		e.printStackTrace();
    	}
    	return redirectPage;
	}
	
	///PC端电商支付---------------------------
	/**
	 * 支付宝支付手机网页支付订单提交封装
	 * @param dealIndent
	 * @param appId
	 * @param userId
	 * @return
	 */
	public static String alipaySubmit_PC(Order order, int param1, Object... params){
		//req_data详细信息
		String url=Global.getWebUrlPath()+"/shops";
		//服务器异步通知页面路径
		String notify_url = url+"/pay/alipaywx/notify";
		//需http://格式的完整路径，不能加?id=123这类自定义参数

		//页面跳转同步通知页面路径
		String call_back_url = url+"/pay/alipaypc/callback?type="+param1;
		
		String redirectPage = "";
		// 把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", "01");
		sParaTemp.put("return_url", call_back_url);
		sParaTemp.put("seller_email", AlipayConfig.seller_email);
		sParaTemp.put("out_trade_no", order.getOrderNo());
		sParaTemp.put("subject", "乐活社区电商系统在线支付");
		double total_fee = order.getAmount();
		sParaTemp.put("total_fee", String.valueOf(String.format("%.2f",total_fee)));
		sParaTemp.put("body", "");
		sParaTemp.put("show_url", "www.9ievent.com");

		// 先调用接口支付，如果返回的值是支付成功，则进行下一步，如果失败则返回。
		redirectPage = com.neusoft.lohas.common.pay.payutil.alipay.util.AlipaySubmit
				.buildRequestSelf(sParaTemp, "get", "确认");
		// 如果支付成功，则将交易记录插入进入表。记录下来。并且将返回的值展示出来。
		// 生成订单，并记录下来
		return redirectPage;
	}
	
	/**
	 * 银联支付手机网页支付订单提交封装
	 * @param request
	 * @param dealIndent
	 * @param appId
	 * @param userId
	 * @return
	 */
	public static String unionpaySubmit_PC(HttpServletRequest request, Order order, Object... params){
		String redirectPage="";
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		java.util.Date currentTime = new java.util.Date();//得到当前系统时间 
		Date outDate = new Date(currentTime.getTime() + 5 * 60 * 1000);
		String pDate = formatter.format(currentTime);
		String oDate = formatter.format(outDate);
		//前台跳转地址
		String frontUrl = Global.getWebUrlPath();
		if (params.length>0) {
			frontUrl = Global.getWebUrlPath()+"/shops/shoping/myOrder/orderList";
		}
		String backUrl = Global.getWebUrlPath()+"/shops/pay/unionPaywx/selfUnionPayBack";
		RemoteAccessor remoteAccessor = new RemoteAccessor();
    	try{
    		double amounts = order.getAmount();
	    	String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
	    			"<upbp application=\"MGw.Req\" version =\"1.0.0\" sendTime =\""+pDate+"\" sendSeqId =\"00000888888000\">" +
	    			"<frontUrl>"+frontUrl+"</frontUrl><merchantOrderDesc></merchantOrderDesc><misc></misc>" +
	    			"<gwType>01</gwType><transTimeout>"+oDate+"</transTimeout><backUrl>"+backUrl+"</backUrl>" +
	    			"<merchantOrderCurrency>156</merchantOrderCurrency><merchantOrderAmt>"+new java.text.DecimalFormat("0").format(Double.valueOf(amounts*100))+"</merchantOrderAmt>" +
	    			"<merchantOrderDesc>商品订购</merchantOrderDesc>"+
	    			"<merchantName>乐活社区电商系统在线支付</merchantName><merchantId>802310048993225</merchantId><merchantOrderTime>"+pDate+"</merchantOrderTime>" +
	    			"<merchantOrderId>"+order.getOrderNo()+"</merchantOrderId><merchantUserId></merchantUserId>" +
	    			"<mobileNum>"+order.getUser().getMobile()+"</mobileNum>" +
	    			"<cardNum></cardNum></upbp>";
	    	BASE64Encoder encoder = new BASE64Encoder();
	    	BASE64Decoder decoder = new BASE64Decoder();
	    	String merchantId = encoder.encodeBuffer("802310048993225".getBytes());
	    	String mm = MD5.getHashString("654321");
	    	String keyPath = request.getRealPath("/") + "unionpay/802310048993225.pfx";
	    	String privateKey = EncDecUtil.getCertKey("123456",keyPath);
	    	String desKey = encoder.encodeBuffer(RSACoder.encryptByPrivateKey(mm.getBytes(), decoder.decodeBuffer(privateKey)));
	    	byte[] bodyb = DesUtil2.encrypt(data.getBytes("utf-8"), mm.getBytes());
	    	String miBody = encoder.encode(bodyb);
	    	String xml = merchantId + "|" + desKey + "|" + miBody;
	    	String re = remoteAccessor.getResponseByStream("http://upwap.bypay.cn/gateWay/gate.html", "utf-8", xml);
	    	//System.out.println("返回结果："+re);
	    	String[] strArr = re.split("\\|");
	    	byte[] de = decoder.decodeBuffer(strArr[1]);
	    	byte[] b = DesUtil2.decrypt(de, mm.getBytes());
	    	String content = new String(b,"utf-8");
	    	//System.out.println(content);
	    	Document document = DocumentHelper.parseText(content);
	    	Element upbp = document.getRootElement();
	    	redirectPage = upbp.elementText("gwInvokeCmd");
	    	//System.out.println("重定向地址：");
	    	//System.out.println(redirectPage);
    	}catch (Exception e) {
    		e.printStackTrace();
    	}
    	return redirectPage;
	}
}
